﻿using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows;
using Foundation;
using Foundation.MarkupExtensions;
using Loader;
using Poet.Modules;
using Poet.Properties;
using Poet.Resources;
using Poet.ViewModels;
using Poet.Views;

namespace Poet
{
    public class AppLoader
    {
        static AppLoader()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            AppDomain.CurrentDomain.ResolveAssemblies<Assemblies>();
            Initialize();
        }

        public AppLoader(Application application)
        {
            const string uriString = "/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml";
            application.Resources.MergedDictionaries.Add(new ResourceDictionary
                {
                    Source = new Uri(uriString, UriKind.Relative)
                });
        }

        public static AppLoader Current { get; private set; }
        public StartupEventArgs StartupEventArgs { get; private set; }

        public void Run(object sender, StartupEventArgs e)
        {           
            Current = this;
            StartupEventArgs = e;
            var args = e.Args.ToList();
            if (!InstanceManager.CanCreateInstance(args))
                Application.Current.Shutdown();

            //System.Diagnostics.PresentationTraceSources.DataBindingSource.Switch.Level =
                //System.Diagnostics.SourceLevels.Critical;
            System.Windows.Forms.Application.EnableVisualStyles();
            var configuration = ConfigurationManager.OpenExeConfiguration(InstanceManager.ExecutableFilePath);
            if (!configuration.HasFile)
                File.WriteAllText(configuration.FilePath, Properties.Resources.app_config);

            LocalizingManager.Initialize();
            if (Settings.Default.Language.ToLower().Contains("ru"))
                Localizing.Managers.Add(RussianResource.ResourceManager);

            Application.Current.MainWindow = new WelcomeView();
            Application.Current.MainWindow.Show();
            ThemeManager.EnableVisualStylesForWinFormsControls();
            FileNameProvider.BaseDirectory =
                PathProvider.BaseDirectory +
                Settings.Default.BaseSerializationDirectory;

            var mainViewModel = Store.OfType<TrunkViewModel>();
            var trayView = Store.OfType<TrayView>();
            var mainView = Store.OfType<TrunkView>();
            trayView.DataContext = mainViewModel;
            mainView.DataContext = mainViewModel;
            mainView.Activated += mainViewModel.OnFirstTimeActivated;
            if (args.Contains("-minimized", StringComparer.OrdinalIgnoreCase))
                mainView.WindowState = WindowState.Minimized;

            Application.Current.MainWindow.Close();
            Application.Current.MainWindow = mainView;
            mainView.Show();
            trayView.Show();

            if (args.Count == 0)
                mainView.Focus();
        }

        private static void Initialize()
        {
            var resourceAssembly = Assembly.GetAssembly(typeof(AppLoader));
            Picture.Managers.Add(new PictureManager(resourceAssembly, "Resources/IconSet"));
            Picture.Managers.Add(new PictureManager(resourceAssembly, "Resources"));
        }
    }
}
